package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.Session;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();

        //排除异常情况 购物车为空 用户地址为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        List<ShoppingCart> cartList = shoppingCartMapper.select(shoppingCart);
        if (cartList == null || cartList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //插入订单表数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        //未实现微信支付功能，直接设为待接单状态
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        orderMapper.insert(orders);

        //插入订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();

            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车
        shoppingCartMapper.delete(userId);

        //封装 orderSubmitVO
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();

        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setId(orders.getId());

        //通过websocket向客户端推送消息 type orderId content
        Map map = new HashMap();

        map.put("type", 1);// 1 表示来单提醒， 2 表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号：" + orders.getNumber());

        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);

        return orderSubmitVO;


    }

    /**
     * ；历史订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult orderHistoryPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页规则
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        //根据 userId 查询
        Long userId = BaseContext.getCurrentId();
        List<Orders> orders = orderMapper.orderHistoryPageQuery(userId);

        Page<OrderVO> orderVOList = new Page<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);

            //根据 userId orderId 查询order_detail
            Long orderId = order.getId();
            List<OrderDetail> orderDetailList =  orderDetailMapper.selectBatch(orderId);

            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }

        return new PageResult(orderVOList.getTotal(), orderVOList.getResult());
    }

    /**
     * 根据 orderId查询 订单
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetail(Long id) {
        //查询 orders 表
        Orders order = orderMapper.selectById(id);

        //查询 orderDetail 表
        List<OrderDetail> orderDetailList = orderDetailMapper.selectBatch(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        // 根据ID查询订单更改订单状态
        Orders order = new Orders();
        order.setStatus(Orders.CANCELLED);
        order.setId(id);
        order.setCancelTime(LocalDateTime.now());
        order.setCancelReason("用户取消");
        orderMapper.update(order);
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        //条件查询

        Page<Orders> ordersList =  orderMapper.conditionQuery(ordersPageQueryDTO);

        return new PageResult(ordersList.getTotal(), ordersList.getResult());
    }

    /**
     * 订单状态统计
     * @return
     */
    @Override
    public OrderStatisticsVO orderStatistics() {
        //根据订单状态查询
        Integer confirmed = orderMapper.selectByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.selectByStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed = orderMapper.selectByStatus(Orders.TO_BE_CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        //根据订单ID修改订单状态
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO,order);
        orderMapper.update(order);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders order = new Orders();
        order.setStatus(Orders.CANCELLED);
        order.setCancelTime(LocalDateTime.now());
        BeanUtils.copyProperties(ordersRejectionDTO,order);
        orderMapper.update(order);
    }

    /**
     * 管理端取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO,order);
        order.setStatus(Orders.CANCELLED);
        order.setCancelTime(LocalDateTime.now());

        orderMapper.update(order);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.COMPLETED);
        orderMapper.update(order);
    }
}
